﻿//Copyright (C) <2013>  <jonathan cleeve norton> All Rights Reserved 
//Contact jon.norton@fin-plus.co.uk website <http://www.fin-plus.co.uk/>
using System;
using System.Collections.Generic;
using System.Linq;
using log = Logger.Logger;

namespace FinPlusCommon
{
    public class Groups : Dictionary<string, string>
    {
        private enum Params { FunctionName, FunctionMap, Name, Group }
        private readonly IFunctions _group;

        //construct
        public Groups(IFunctions funcs)
        {
            _group = funcs;
            _group.FuncUpdate += Group_Update;

            lock (_group)
            {
                foreach (var func in _group.Values.Where(f => f[Params.FunctionName.ToString()].Equals(Params.FunctionMap.ToString())))
                    this[(string)func[Params.Name.ToString()]] = (string)func[Params.Group.ToString()];
            }
        }

        //event
        private void Group_Update(object s, ItemEventArgs a)
        {
            try
            {
                var func = (IFunction)s;

                //note should only send group map collections
                if (!func[Params.FunctionName.ToString()].ToString().Equals(Params.FunctionMap.ToString())) return;
  
                lock (_group)
                {
                    if (a.ChangeType == ChangeType.Removed)
                        this.Remove(func[Params.Name.ToString()].ToString());
                    else if (a.ChangeType == ChangeType.New || a.ChangeType == ChangeType.Altered)
                        this[func[Params.Name.ToString()].ToString()] = func[Params.Group.ToString()].ToString();
                }
            }
            catch(Exception e)
            {
                log.Log(Logger.Level.Error, "NA", "NA", e.Message, e);
            }
        }
    }
}
